import 'package:date_format/date_format.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:mziot/app/data/group_down_entity.dart';
import 'package:mziot/app/data/scene_params_entity.dart';
import 'package:mziot/app/modules/devices/device_provider.dart';
import 'package:mziot/app/modules/devices/views/chose_scene_view.dart';
import 'package:mziot/app/modules/scene/scene_provider.dart';
import 'package:mziot/app/tools/blue_service.dart';
import 'package:mziot/app/tools/tools.dart';
import 'package:mziot/generated/locales.g.dart';

class SceneDetailController extends GetxController {
  TextEditingController nameController = TextEditingController();
  TextEditingController noteController = TextEditingController();

  SceneProvider provider = SceneProvider();
  DeviceProvider deviceProvider = DeviceProvider();
  List<GroupDownEntity>? groupList;
  var openChoose = false;
  final selectText = ''.obs;
  int? sceneId;
  int timeRate = 10;

  final sceneInfo = SceneParamsEntity().obs;
  final light = 10.obs;
  final selectLeft = true.obs;
  final selectDate = false.obs;
  final dateStart = DateTime.now().obs;
  final dateEnd = DateTime.now().obs;
  final infoChange = false.obs;

  @override
  void onInit() {
    super.onInit();

    sceneId = Get.arguments;
    if (sceneId != null) {
      fetchSceneDetail();
    }
    fetchGroupList();
  }

  @override
  void onReady() {
    super.onReady();
  }

  void updateDate() {
    final startDate = dateStart.value.millisecondsSinceEpoch;
    final endDate = dateEnd.value.millisecondsSinceEpoch;

    if (startDate > endDate) {
      showToast(LocaleKeys.tips_end_time.tr);
      return;
    }
    if (selectDate.value) {
      sceneInfo.value.startTime = formatDate(dateStart.value, [yyyy, '-', mm, '-', dd]);
      sceneInfo.value.endTime = formatDate(dateEnd.value, [yyyy, '-', mm, '-', dd]);
    } else {
      SceneParamsLightOffs momentVo = SceneParamsLightOffs();
      momentVo.start = formatDate(dateStart.value, [HH, ':', nn]);
      momentVo.end = formatDate(dateEnd.value, [HH, ':', nn]);
      momentVo.rate = timeRate;
      if (sceneInfo.value.lightOffs != null) {
        sceneInfo.value.lightOffs?.add(momentVo);
      } else {
        sceneInfo.value.lightOffs = [];
        sceneInfo.value.lightOffs?.add(momentVo);
      }
    }
    infoChange.value = !infoChange.value;
    Get.back(result: true);
  }

  void updateLight(int? rate, int index) {
    sceneInfo.value.lightOffs?[index].rate = rate;
    infoChange.value = !infoChange.value;
  }

  void deleteAction(int index) {
    sceneInfo.value.lightOffs?.removeAt(index);
    infoChange.value = !infoChange.value;
  }

  void editAction() {
    if (sceneInfo.value.sceneName == null || sceneInfo.value.sceneName!.isEmpty) {
      showToast(LocaleKeys.scene_name.tr);
      return;
    }
    if (sceneInfo.value.startTime == null || sceneInfo.value.startTime!.isEmpty) {
      showToast(LocaleKeys.scene_time.tr);
      return;
    }
    if (sceneInfo.value.lightOffs == null || sceneInfo.value.lightOffs!.isEmpty) {
      showToast(LocaleKeys.scene_light_on.tr);
      return;
    }
    bool isEmpty = false;
    sceneInfo.value.lightOffs?.forEach((element) {
      if (element.rate == null) {
        isEmpty = true;
        return;
      }
    });
    if (isEmpty) {
      showToast('10~100');
      return;
    }
    sceneInfo.value.lightRate ??= 0;
    sceneInfo.value.isLock ??= false;

    provider.editScene(sceneInfo.value).then((value) {
      if (value.isSuccess) {
        Get.back(result: true);
        BlueService.share.execCmds(value.data);
      }
      showToast(value.msg ?? '');
    });
  }

  void openChooseAction() {
    if (groupList?.isEmpty ?? true && !openChoose) {
      openChoose = true;
      fetchGroupList();
      return;
    }
    openChoose = false;
    groupList = groupList?.map((e) {
      sceneInfo.value.groupIds?.forEach((element) {
        if (element == e.id) {
          e.isSelected.value = true;
        }
      });
      return e;
    }).toList();
    Get.dialog(
      ChoseSceneView(
        false,
        groupList,
        [],
        [],
        (value) {
          final groups = value as List<GroupDownEntity>;
          selectText.value = groups.map((e) => e.groupName).join(', ');
          sceneInfo.value.groupIds = groups.map((e) => e.id!).toList();
          infoChange.value = !infoChange.value;
        },
        isMutile: true,
      ),
      useSafeArea: false,
    );
  }

  void fetchSceneDetail() {
    if (sceneInfo.value.sceneName?.isEmpty ?? true) {
      EasyLoading.show();
    }
    provider.takeSceneInfo(sceneId!).then((value) {
      if (value.isSuccess) {
        sceneInfo.value.sceneName = value.data?.sceneName;
        selectText.value = value.data?.groupNames?.join(',') ?? '';
        DateFormat format = DateFormat("MM-dd-yyyy HH:mm:ss");

        final startTime = format.parse(value.data?.sceneStartTime ?? '');
        final endTime = format.parse(value.data?.sceneEndTime ?? '');
        final startStr = formatDate(startTime, [yyyy, '-', mm, '-', dd]);
        final endStr = formatDate(endTime, [yyyy, '-', mm, '-', dd]);
        sceneInfo.value.id = value.data?.id;
        sceneInfo.value.startTime = startStr;
        sceneInfo.value.endTime = endStr;
        sceneInfo.value.groupIds = value.data?.groupIds;
        sceneInfo.value.lightRate = value.data?.lightRate ?? 10;
        sceneInfo.value.isLock = value.data?.lockStatus;
        sceneInfo.value.remark = value.data?.remark;

        value.data?.momentVo?.forEach((element) {
          SceneParamsLightOffs momentVo = SceneParamsLightOffs();
          momentVo.start = element.start;
          momentVo.end = element.end;
          momentVo.id = element.id;
          momentVo.rate = element.lightRate ?? 10;
          sceneInfo.value.lightOffs ??= [];
          sceneInfo.value.lightOffs?.add(momentVo);
        });
        infoChange.value = !infoChange.value;
        nameController.text = sceneInfo.value.sceneName ?? '';
        noteController.text = sceneInfo.value.remark ?? '';
      }
    }).whenComplete(() => EasyLoading.dismiss());
  }

  void fetchGroupList() {
    deviceProvider.takeGroupDownList().then((value) {
      if (value?.isSuccess ?? false) {
        groupList = value?.data;
        if (openChoose) {
          openChooseAction();
        }
      } else {
        showToast(value?.msg ?? '');
      }
    });
  }

  @override
  void onClose() {
    noteController.dispose();
    nameController.dispose();
  }
}
